package view;

import model.Borrower;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Collection;

public class BorrowerSelectionDialog extends JDialog {
    private Borrower selectedBorrower;
    private final JComboBox<Borrower> borrowerCombo;

    public BorrowerSelectionDialog(JFrame parent, String title, Collection<Borrower> borrowers) {
        super(parent, title, true);
        setSize(400, 200);
        setLocationRelativeTo(parent);

        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 标题
        JLabel titleLabel = new JLabel("选择借阅者:");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        mainPanel.add(titleLabel, BorderLayout.NORTH);

        // 借阅者选择
        borrowerCombo = new JComboBox<>();
        borrowerCombo.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                          boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof Borrower) {
                    Borrower b = (Borrower) value;
                    setText(String.format("%s - %s", b.getId(), b.getName()));
                }
                return this;
            }
        });

        for (Borrower borrower : borrowers) {
            borrowerCombo.addItem(borrower);
        }

        mainPanel.add(new JScrollPane(borrowerCombo), BorderLayout.CENTER);

        // 按钮区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        JButton okButton = new JButton("确定");
        okButton.addActionListener(this::selectBorrower);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void selectBorrower(ActionEvent e) {
        selectedBorrower = (Borrower) borrowerCombo.getSelectedItem();
        dispose();
    }

    public Borrower getSelectedBorrower() {
        return selectedBorrower;
    }
}